package cn.micro.eye.commons.mybatis;

import cn.micro.eye.commons.auth.AuthContext;
import cn.micro.eye.commons.auth.TokenBody;
import cn.micro.eye.commons.entity.MicroEntity;
import cn.micro.eye.commons.utils.IPUtils;
import cn.micro.eye.type.DeletedEnum;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.sql.Timestamp;

/**
 * The Auto Fill Meta Data Object Handler
 *
 * @author lry
 */
@Slf4j
@Configuration
public class GlobalAutoFillHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String operator = this.getOperator();

        this.setFieldValByName(MicroEntity.CREATED_AT_NAME, timestamp, metaObject);
        this.setFieldValByName(MicroEntity.CREATED_BY_NAME, operator, metaObject);
        this.setFieldValByName(MicroEntity.UPDATED_AT_NAME, timestamp, metaObject);
        this.setFieldValByName(MicroEntity.UPDATED_BY_NAME, operator, metaObject);
        this.setFieldValByName(MicroEntity.DELETED_NAME, DeletedEnum.UN_DELETE.getValue(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String operator = this.getOperator();

        this.setFieldValByName(MicroEntity.UPDATED_AT_NAME, timestamp, metaObject);
        this.setFieldValByName(MicroEntity.UPDATED_BY_NAME, operator, metaObject);
    }

    private String getOperator() {
        TokenBody tokenInfo = AuthContext.getContextAccessToken();
        if (tokenInfo == null || tokenInfo.getUserId() == null) {
            return IPUtils.getIPAddress();
        }

        return String.valueOf(tokenInfo.getUserId());
    }

}
